<style scoped lang="scss">
.buttom-bar {
  width: 10rem;
  height: 7vh;
  display: flex;
  @include flex-space-between-center;
  color: #fff;
  position: fixed;
  bottom: 0;
  left: 0;
  border-top: 1px solid rgba(41, 40, 37, 0.8);
  background-color: #242630;

  .buttom-bar-input {
    width: 7.6533rem;
    height: 1.2rem;
    @include flex-center;

    input {
      width: 7.2rem;
      padding-left: .4533rem;
      height: 1.2rem;
      border: none;
      outline: none;
      font-size: .3733rem;
      background-color: transparent;
      caret-color: #face15;
      color: #fff;
    }
  }

  .buttom-bar-mention {
    width: 1.1733rem;
    height: 1.1733rem;
    @include flex-center;
    font-size: .56rem;
  }

  .buttom-bar-send {
    width: 1.1733rem;
    height: 1.1733rem;
    @include flex-center;
    font-size: .56rem;
  }
}

.message-list {
  flex: 1; // 占满剩余空间
  height: 85vh;
  padding: 0.5rem;
  overflow-y: auto; // 消息过多时滚动
  padding-bottom: 7vh;

  // 时间分割线（居中显示）
  .time-divider {
    text-align: center;
    font-size: 0.3rem;
    color: #888;
    margin: 0.5rem 0;
  }

  // 消息项容器（Flex布局控制对齐）
  .message-item {
    display: flex;
    margin: 0.3rem 0;
    align-items: flex-end; // 消息底部对齐

    // 头像样式
    .avatar {
      width: 1rem;
      height: 1rem;
      border-radius: 50%;
      margin: 0 0.3rem;
    }

    // 消息气泡基础样式
    .message-bubble {
      max-width: 70%; // 限制最大宽度，避免过宽
      padding: 0.3rem 0.4rem;
      border-radius: 0.2rem;
      font-size: 0.4rem;
      word-wrap: break-word; // 长文本换行
    }
  }

  // 自己的消息（居右）
  .self-message {
    justify-content: flex-end; // 整体右对齐

    .avatar {
      order: 2; // 头像放在气泡右边
    }

    .message-bubble {
      background-color: #face15; // 自己的气泡色（黄色）
      color: #000; // 文字深色
      border-top-right-radius: 0.05rem; // 右上角略平，更自然
    }
  }

  // 对方的消息（居左）
  .other-message {
    justify-content: flex-start; // 整体左对齐

    .avatar {
      // 删除 order: 1，保留其他样式
      width: 1rem;
      height: 1rem;
      border-radius: 50%;
      margin: 0 0.3rem; // 右边距，与气泡隔开
    }

    // 气泡默认在头像右侧（无需额外order）
    .message-bubble {
      background-color: #242630;
      color: #fff;
      border-top-left-radius: 0.05rem;
    }
  }
}
</style>
<template>
  <div class="chat-with">
    <PageTitleBar :title="userNickname" />
  </div>

  <div class="message-list" ref="messageListRef">
    <!-- 时间分割线（可选） -->
    <div class="time-divider" v-if="showTimeDivider">昨天 19:33</div>

    <!-- 消息项：循环渲染 -->
    <div class="message-item" v-for="item in messageStore.currentChatMessages" :key="item.id"
      :class="{ 'self-message': item.fromId === userId, 'other-message': item.fromId !== userId }">
      <!-- 头像：自己的消息在右，对方的在左 -->
      <img class="avatar" :src="`http://43.138.15.137:3000${targetUserimg}`" alt="头像" v-if="item.fromId !== userId">
      <img class="avatar" :src="`http://43.138.15.137:3000${userAvatar}`" alt="头像" v-else>

      <!-- 消息气泡 -->
      <div class="message-bubble">
        {{ item.content || item.privateLetterContent }}
      </div>
    </div>
  </div>

  <div class="buttom-bar">
    <div class="buttom-bar-input">
      <input type="text" placeholder="发送消息..." v-model="messageContent" @keydown.enter="sendMessage" />
    </div>
    <!-- 艾特按钮 -->
    <div class="buttom-bar-mention">
      <i class="iconfont icon-aite"></i>
    </div>
    <!-- 发送按钮 -->
    <div class="buttom-bar-send">
      <i class="iconfont icon-dui" @click="sendMessage"></i>
    </div>
  </div>
  <!-- 聊天内容区域 -->
</template>
<script setup>
import PageTitleBar from '../../components/common/PageTitleBar.vue'
import { getPrivateLetter, sendPrivateLetter } from '@/api/ChatWith/ChatWith'
import { useUserStore } from '@/store/modules/user/user'
import { getUserInfoAPI } from '@/api/user/user'
import { useRoute } from 'vue-router';
import { useMessageStore } from '@/store/modules/message/message'
// 依赖注入
const socket = inject('socket')
const route = useRoute();
const messageStore = useMessageStore()
const userStore = useUserStore();

// 路由参数
const targetUserId = route.query.targetUserId;
const targetUserimg = route.query.targetUserimg;
const userNickname = route.query.userNickname;
// 本地状态
const userId = userStore.userInfo.userId;
const userAvatar = ref('')
const messageContent = ref('');
// 用户名
const username = ref('');
const messageListRef = ref(null)
const messageList = ref([]);
const showTimeDivider = ref(true);

// 滚动到最底部
function scrollToBottom() {
  nextTick(() => {
    const listEl = messageListRef.value;
    if (listEl) {
      listEl.scrollTop = listEl.scrollHeight;
    }
  });
}
// 初始化聊天列表
async function loadHistoryMessages() {
  if (!userId || !targetUserId) return;
  try {
    const res = await getPrivateLetter(userId, targetUserId)
    if (res.code === 200) {
      const formattedMessages = res.data.map(item => ({
        id: item.id,
        fromId: item.fromId,
        toId: item.toId,
        content: item.privateLetterContent, // 统一为content字段
        createdAt: item.createTime,
        isRead: item.isRead
      }))
      messageList.value = formattedMessages
      messageStore.initCurrentChat(targetUserId, formattedMessages)
      scrollToBottom()
    }
  } catch (error) {
    console.log(error);
  }
}

async function sendMessage() {
  const content = messageContent.value.trim()
  if (!content || !userId || !targetUserId) return;
  try {
    const res = await sendPrivateLetter(userId, targetUserId, {
      fromUserId: userId,
      content: messageContent.value,
      toUserId: targetUserId
    })
    messageContent.value = ''
    if (res.code === 200) {
      console.log(userAvatar.value);
      messageStore.sendChatMessage(targetUserId, content, targetUserimg, userNickname);
    }
    scrollToBottom()
  } catch (error) {
    console.log(error);
  }
}
async function loadUserAvatar() {
  try {
    const res = await getUserInfoAPI(userId)
    if (res.code === 200) {
      userAvatar.value = res.data.userAvatar
      username.value = res.data.userNickname
    }
  } catch (error) {
    console.log('加载头像失败：', error);
  }
}


// 监听接收私有消息事件
onMounted(async () => {
  await nextTick(); // 确保userStore.userInfo已初始化
  // 加载历史消息
  loadHistoryMessages();
  // 加载目标用户昵称
  loadUserAvatar();
})
onBeforeUnmount(() => {
  messageStore.clearCurrentChat()
});
watch(
  () => messageStore.currentChatMessages,
  () => {
    scrollToBottom()
  },
  { deep: true }
)
</script>